<template>
	<up-upload :fileList="internalFileList" @afterRead="handleAfterRead" @delete="handleDelete" :name="name" :multiple="multiple" :maxCount="maxCount" :accept="accept"></up-upload>
</template>

<script setup>
	import { ref, watch, defineProps, defineEmits, nextTick } from 'vue';

	import { port, imgUrl, hint } from '/service/port';
	import { onShow } from '@dcloudio/uni-app';

	const qiNiuInfo = ref('');

	const props = defineProps({
		modelValue: {
			type: Array,
			default: () => []
		},
		accept: {
			type: String,
			default: 'image'
		},
		maxCount: {
			type: Number,
			default: 10
		},
		multiple: {
			type: Boolean,
			default: true
		},
		name: {
			type: String,
			default: 'file'
		},
		formData: {
			type: Object,
			default: () => ({})
		},
		headers: {
			type: Object,
			default: () => ({})
		}
	});

	const emits = defineEmits(['update:modelValue', 'success', 'error', 'delete', 'change']);

	const internalFileList = ref([...props.modelValue]);

	// 同步外部传入的modelValue
	watch(
		() => props.modelValue,
		(newVal) => {
			internalFileList.value = [...newVal];
		}
	);

	// 触发文件列表更新
	const triggerUpdate = () => {
		emits('update:modelValue', [...internalFileList.value]);
		emits('change', [...internalFileList.value]);
	};

	const handleDelete = (event) => {
		internalFileList.value.splice(event.index, 1);
		triggerUpdate();
		emits('delete', event);
	};

	const handleAfterRead = async (event) => {
		const newFiles = [].concat(event.file);
		const startIndex = internalFileList.value.length;

		newFiles.forEach((file) => {
			internalFileList.value.push({
				...file,
				status: 'uploading',
				message: '上传中'
			});
		});

		triggerUpdate();

		for (let i = 0; i < newFiles.length; i++) {
			const index = startIndex + i;
			try {
				const result = await uploadFile(newFiles[i].url, newFiles[i]);

				internalFileList.value[index] = {
					...newFiles[i],
					status: 'success',
					message: '',
					url: result
				};

				emits('success', {
					file: newFiles[i],
					response: result,
					index: index
				});
			} catch (error) {
				internalFileList.value[index] = {
					...newFiles[i],
					status: 'failed',
					message: '上传失败'
				};

				emits('error', {
					file: newFiles[i],
					error: error,
					index: index
				});
			}
			triggerUpdate();
		}
	};

	const uploadFile = async (filePath, file) => {
		
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: imgUrl + 'api/uploads/image',
				filePath,
				name: 'file',
			
				success: (res) => {
					try {
						const data = JSON.parse(res.data)
						if (data.code === 1) {
							resolve(data.data.url)
						} else {
							hint(data.msg)
							reject(data)
						}
					} catch (e) {
						resolve(res.data);
					}
				},
				fail: (err) => {
					reject(err);
				}
			});
		});
	};
</script>
